import React, {useState, useEffect} from 'react';
import { Select, message } from 'antd';
import { DeviceGroupListItem } from '../../Equipment/data.d';
import { getGroupList } from '../service';

interface GroupListComponentProps {
  defaultvalue:number;
  value:string;
  disabled:boolean;
  orgId:number;
  selectChange: (values:any) => void;
}

const { Option } = Select;

/**
 * 
 * 所属分组下拉控件
 */
const GroupListComponent: React.FC<GroupListComponentProps> = (props) => {

  const { disabled, defaultvalue,value, orgId, selectChange } = props;
  const [list, setList] = useState([]);
  
  const getList = (orgId:number) =>{
    new Promise((resolve, reject) => {
      getGroupList(orgId)
        .then((res) => {
          if (res && res.code === 200) {
            setList(res.data);
            resolve(true);
          } else {
            message.error('请求失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  }
  
  return (
      <Select
        disabled={disabled}
        showSearch
        className="groupSelect"
        placeholder="请选择所属分组"
        optionFilterProp="children"
        defaultValue={defaultvalue>0?defaultvalue:null}
        value={value}
        allowClear
        style={{ width: 200 }}
        onChange={(values) =>selectChange(values)}
        onFocus={() => getList(orgId)}
      >
        {list.map((item:DeviceGroupListItem) => <Option key={item.id} value={item.id}>{item.name}</Option>)}
    </Select>
  );
};

export default GroupListComponent;
